package util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.ProtectionDomain;

/**
 * Extracts a host from hosts file in db package
 * 
 * @author Emil Wall
 * @version 1.0
 */
public class HostFile {
	
	private static final int BUFFER_SIZE = 1000;
	
	/**
	 * 
	 * @param file e.g. "db/hosts"
	 * @return BufferedReader to specified file
	 */
	private BufferedReader getFileReader(String file) {
		ProtectionDomain pd = this.getClass().getProtectionDomain();
		String path = pd.getCodeSource().getLocation().getPath();
		FileInputStream f = null;
		try {
			f = new FileInputStream(path+file);
		} catch (FileNotFoundException e) {
			if(Debug.verbose) {
				e.printStackTrace();
			}
		}
		DataInputStream d = new DataInputStream(f);
		return new BufferedReader(new InputStreamReader(d));
	}
	
//	/**
//	 * Extract a single host from the hosts file
//	 * @return String representation of host name
//	 */
//	public static String getHost() {
//		BufferedReader b = new HostFile().getFileReader("db/hosts");
//		String line;
//		try {
//			while((line = b.readLine()) != null) {
//				if(line.startsWith("#")) { 
//					// Skip comment lines
//				} else if(line.equals("localhost")) {
//					// Skip localhost
//				} else {
//					b.close();
//					return line;
//				}
//			}
//			b.close();
//		} catch (IOException e) {
//			if(Debug.verbose) {
//				e.printStackTrace();
//			}
//		}
//		return "localhost";
//	}
	
	/**
	 * Extract all hosts from the hosts file
	 * @return String array containing the host names
	 */
	public static String[] getHosts() {
		BufferedReader b = new HostFile().getFileReader("db/hosts");
		String[] buffer = new String[BUFFER_SIZE];
		int index = 0;
		String line;
		try {
			while((line = b.readLine()) != null) {
				if(!line.startsWith("#")) { // Skip comment lines
					buffer[index++] = line; // Store the host names in buffer
				}
			}
			b.close();
		} catch (IOException e) {
			if(Debug.verbose) {
				e.printStackTrace();
			}
		}
		String[] res = new String[index];
		System.arraycopy(buffer, 0, res, 0, index); // Trim to size
		return res;
	}
	
	/**
	 * Reads from hosts file and prints to stdout
	 * 
	 * @param args ignored
	 */
	public static void main(String[] args) {
		Print.array(getHosts());
	}

}
